package com.ptu.spzx.gateway.service.impl;

import cn.hutool.core.lang.UUID;
import com.google.code.kaptcha.Producer;

import com.ptu.spzx.constant.CacheConstant.CacheConstants;
import com.ptu.spzx.gateway.Excpetion.GatewayAuthException;
import com.ptu.spzx.gateway.service.ValidateCodeService;
import com.ptu.spzx.gateway.util.RedisCache;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.model.vo.system.ValidateCodeVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Autowired
    //redis注入
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @Override
    public Result createCaptcha() throws IOException {
        // 保存验证码信息
        String uuid = UUID.randomUUID().toString().replace("-","");;
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        capStr = code = captchaProducer.createText();
        image = captchaProducer.createImage(capStr);
        System.out.println("=============");
        System.out.println(code);
        System.out.println("=============");
        redisCache.setCacheObject(verifyKey, code, CacheConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Result.build(e.getMessage(), ResultCodeEnum.ERROR);
        }
        ValidateCodeVo validateCodeVo=new ValidateCodeVo();
        validateCodeVo.setCodeKey(uuid);
        validateCodeVo.setCodeValue("data:image/png;base64,"+image);
        return Result.build(validateCodeVo,ResultCodeEnum.SUCCESS);
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) {
        if (!StringUtils.hasText(code)) {
            throw new GatewayAuthException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid))
        {
            throw new GatewayAuthException("验证码已失效");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new GatewayAuthException("验证码错了");
        }
    }
}
